package com.smart.seckilldemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 *  自定义限流
 *
 * @author mtl
 */

@Slf4j
@Component
public class CurrentUtils {

    @Resource
    RedisTemplate redisTemplate;

    public Boolean current(HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        Object obj = redisTemplate.opsForValue().get("ip:" + remoteAddr);
        if(obj==null){
            redisTemplate.opsForValue().set("ip:" + remoteAddr,"busy",300, TimeUnit.MILLISECONDS);
            return true;
        }else {
            log.info(remoteAddr+"触发了限流");
            return false;
        }

    }

}
